﻿using GKQC.Common;
using GKQC.DbHelper.DbModels;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.Util;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;

namespace GKQC.Ort.Reports
{
    /// <summary>
    /// 信赖性试验：其他报表汇总
    /// </summary>
    public class R000: BaseReport
    {
        public static StringBuilder msg = new StringBuilder();
        public static void GenReportSheet(IWorkbook workbook, ISheet sheet, OrtHeadModel head)
        {
            #region 表头

            try
            {
                //sheet.GetRow(5).GetCell(0).SetCellValue(sheet.GetRow(5).GetCell(0).StringCellValue + head.Pn);
                //sheet.GetRow(32).GetCell(8).SetCellValue(sheet.GetRow(32).GetCell(8).StringCellValue + DateTime.Now.ToString("yyyy-MM-dd"));
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }

            #endregion 表头

            sheet.ForceFormulaRecalculation = true;
        }


        public static IWorkbook GenAllReport(List<OrtHeadModel> heads, List<ReportSetModel> reportSets, string path, bool isCreateFile)
        {
            try
            {
                var rs = reportSets.Where(r => r.Code == "R000");
                if (rs.Count() == 0)
                {
                    MessageBox.Show("無法生成報表，因為报表代号未定義：R000", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return null;
                }
                ReportSetModel reportSet = rs.First();

                string errorMsg = string.Empty;
                string fileName = Settings.GetReportFileName(path, reportSet.Path, out errorMsg);
                if (!string.IsNullOrWhiteSpace(errorMsg))
                {
                    MessageBox.Show(errorMsg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return null;
                }

                string sysTempFileName = Settings.GetTempPath() + "\\"
                + OrtReportFactory.GetExcelTempFileName(heads[0], reportSet)//+ Guid.NewGuid().ToString() 
                + fileName.Substring(fileName.LastIndexOf('.'));
                File.Copy(fileName, sysTempFileName,true);
                IWorkbook workbook = null;
                using (FileStream fs = new FileStream(sysTempFileName, FileMode.Open, FileAccess.Read))  //路径，打开权限，读取权限
                {
                    workbook = WorkbookFactory.Create(new FileInputStream(fs));
                    fs.Close();
                }
                ISheet sheet = workbook.GetSheetAt(0);
                GenReportSheet(workbook, sheet, heads[0]);

                List<ISheet> SheetsExists = new List<ISheet>();

                for (int i = 0; i < heads.Count; i++)
                {
                    var rss = reportSets.Where(r => r.Id == heads[i].ReportId);
                    if (!rss.Any()) continue;
                    ReportSetModel reportSetTemp = rss.First();
                    string reportCode = reportSetTemp.Code;


                    ISheet sheetTemp = null;

                    switch (reportCode)
                    {

                        case "R000":
                            sheetTemp = workbook.GetSheet("汇总");
                            if(sheetTemp == null) sheetTemp = workbook.GetSheet("可靠度試驗總表");
                            break;
                        case "R001":
                            sheetTemp = workbook.GetSheet("高温负载寿命");
                            if (sheetTemp == null) sheetTemp = workbook.GetSheet("高温负载寿命");
                            break;
                        case "R002":
                            sheetTemp = workbook.GetSheet("高温放置寿命");
                            if (sheetTemp == null) sheetTemp = workbook.GetSheet("高温放置寿命");
                            break;
                        case "R003":
                            sheetTemp = workbook.GetSheet("耐焊");
                            if (sheetTemp == null) sheetTemp = workbook.GetSheet("焊锡耐热性");
                            break;
                        case "R004":
                            sheetTemp = workbook.GetSheet("易焊");
                            if (sheetTemp == null) sheetTemp = workbook.GetSheet("易焊锡性　");
                            if (sheetTemp == null) sheetTemp = workbook.GetSheet("易焊锡性");
                            break;
                        case "R005":
                            sheetTemp = workbook.GetSheet("耐濕");
                            if (sheetTemp == null) sheetTemp = workbook.GetSheet("耐濕性");
                            break;
                        case "R006":
                            sheetTemp = workbook.GetSheet("低溫");
                            if (sheetTemp == null) sheetTemp = workbook.GetSheet("低温放置");
                            break;
                        case "R007":
                            sheetTemp = workbook.GetSheet("耐振");
                            if (sheetTemp == null) sheetTemp = workbook.GetSheet("耐振性");
                            break;
                        case "R008":
                            sheetTemp = workbook.GetSheet("溫度循環");
                            if (sheetTemp == null) sheetTemp = workbook.GetSheet("溫度循環");
                            break;
                        case "R009":
                            sheetTemp = workbook.GetSheet("溫特");
                            if (sheetTemp == null) sheetTemp = workbook.GetSheet("温度特性");
                            break;
                        case "R010":
                            sheetTemp = workbook.GetSheet("防爆");
                            if (sheetTemp == null) sheetTemp = workbook.GetSheet("防爆试验");
                            break;
                        case "R011":
                            sheetTemp = workbook.GetSheet("拉力");
                            if (sheetTemp == null) sheetTemp = workbook.GetSheet("端子强度");
                            break;
                        case "R012":
                            sheetTemp = workbook.GetSheet("涌浪电压");
                            if (sheetTemp == null) sheetTemp = workbook.GetSheet("涌浪电压");
                            break;
                        case "R013":
                            sheetTemp = workbook.GetSheet("充放電");
                            if (sheetTemp == null) sheetTemp = workbook.GetSheet("充放电");
                            break;
                        case "R014":
                            sheetTemp = workbook.GetSheet("高溫高濕");
                            if (sheetTemp == null) sheetTemp = workbook.GetSheet("高温高湿");
                            break;
                        default:
                            break;
                    }

                    if (sheetTemp == null) continue;

                    if(!SheetsExists.Contains(sheetTemp))
                        SheetsExists.Add(sheetTemp);

                    System.Reflection.Assembly ass = System.Reflection.Assembly.GetExecutingAssembly();
                    var type = ass.GetType("GKQC.Ort.Reports." + reportCode);
                     
                    //System.Reflection.Assembly ass =
                    //    System.Reflection.Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + "GKQC.Ort.Reports.dll");
                    //Type type = ass.GetType("GKQC.Ort.Reports." + reportCode);
                    var reportClass = Activator.CreateInstance(type);
                    MethodInfo method = reportClass.GetType().GetMethod("GenReportSheet");
                    if (method != null)
                    {
                        try
                        {
                            method.Invoke(reportClass, new object[] { workbook, sheetTemp, heads[i] });
                        }
                        catch(Exception ex)
                        {
                            Logger.LogError(ex);
                            msg.Append(ex.Message);
                        }
                    }

                } // END FOR

                //删除没有的表格
                for(int i= workbook.NumberOfSheets-1; i>=0;i--)
                {
                    ISheet sheetdel = workbook.GetSheetAt(i);
                    if (!SheetsExists.Contains(sheetdel) && sheetdel.SheetName != "匯總" && sheetdel.SheetName != "汇总"
                         && sheetdel.SheetName != "可靠度試驗總表"
                          && sheetdel.SheetName != "可靠度试验总表")
                        workbook.RemoveSheetAt(i);
                }

                if (isCreateFile)
                {
                    using (FileStream fs = new FileStream(sysTempFileName, FileMode.Create, FileAccess.Write))
                    {
                        MemoryStream stream = new MemoryStream();
                        workbook.Write(stream);
                        var buf = stream.ToArray();
                        fs.Write(buf, 0, buf.Length);
                        fs.Flush();
                    }

                    Process.Start(sysTempFileName);
                }

                return workbook;
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
            }

            return null;
        }
    }
}
